import axios from "axios";

interface TongyiResponse {
  request_id: string;
  output: {
    task_id: string;
    task_status: string;
    results: Array<{
      url: string;
    }>;
  };
}
/**
 * 未使用的方法
 */
export async function getTongyiClient() {
  const baseURL = process.env.TY_BASE_URL;
  const apiKey = process.env.TY_API_KEY;
  const wxUri = process.env.TY_WX_URI;

  if (!baseURL || !apiKey || !wxUri) {
    throw new Error("通义配置参数缺失");
  }

  const client = axios.create({
    baseURL,
    headers: {
      Authorization: `Bearer ${apiKey}`,
      "Content-Type": "application/json",
    },
  });

  const pollTaskStatus = async (taskId: string): Promise<string> => {
    const maxAttempts = 30;
    const interval = 2000; // 2秒轮询一次

    for (let i = 0; i < maxAttempts; i++) {
      try {
        const response = await client.get<TongyiResponse>(
          `${wxUri}/api/v1/tasks/${taskId}`
        );
        const status = response.data.output.task_status;

        if (status === "SUCCEEDED") {
          return response.data.output.results[0].url;
        }

        if (status === "FAILED") {
          throw new Error("图片生成失败");
        }

        // 等待下一次轮询
        await new Promise((resolve) => setTimeout(resolve, interval));
      } catch (error) {
        console.error("轮询任务状态失败:", error);
        throw error;
      }
    }
    throw new Error("图片生成超时");
  };

  const generateImage = async (prompt: string) => {
    try {
      const response = await client.post<TongyiResponse>(wxUri, {
        model: "wanx-v1",
        input: {
          prompt,
        },
        parameters: {
          size: "1280*720",
          style: "chinese painting",
        },
      });

      const taskId = response.data.output.task_id;
      if (!taskId) {
        throw new Error("获取任务ID失败");
      }

      return await pollTaskStatus(taskId);
    } catch (error) {
      console.error("通义服务调用失败:", error);
      throw error;
    }
  };

  return {
    generateImage,
  };
}
